package com.quanyan.place.wrapper.impl;

import static com.quanyan.place.service.impl.PlaceBuyServiceImpl.newPlaceBuyContractDetailFromTbDetail;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.validation.constraints.NotNull;

import com.quanyan.place.service.AdminUserService;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.quanyan.api.APIResponse;
import com.quanyan.club.entity.RespPlaceClubInfo;
import com.quanyan.club.service.ClubOpenService;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.place.biz.IBaseService;
import com.quanyan.place.biz.ISearchService;
import com.quanyan.place.cache.PlaceRedisTemplate;
import com.quanyan.place.constants.PlaceConstants;
import com.quanyan.place.entity.PlaceBuyContract;
import com.quanyan.place.entity.PlaceBuyContractDetail;
import com.quanyan.place.entity.TbBizPlace;
import com.quanyan.place.entity.TbBizPlaceBuyContract;
import com.quanyan.place.entity.TbBizPlaceBuyContractDetail;
import com.quanyan.place.entity.TbBizPlaceCategory;
import com.quanyan.place.entity.TbBizPlaceUnit;
import com.quanyan.place.entity.TbBizPlaceUnitSalePlanMain;
import com.quanyan.place.entity.TbBizPlaceUnitSalePlanMainExample;
import com.quanyan.place.entity.TbAdminUser;
import com.quanyan.place.entity.TbCity;
import com.quanyan.place.entity.apireq.ReqContractPay;
import com.quanyan.place.entity.apireq.ReqPlaceContractInfoVo;
import com.quanyan.place.entity.apireq.ReqPlaceInfo;
import com.quanyan.place.entity.apireq.ReqPlaceMessageVo;
import com.quanyan.place.entity.apireq.ReqPlaceSalePlan;
import com.quanyan.place.entity.apiresp.RespPlaceClubActivity;
import com.quanyan.place.entity.apiresp.RespPlaceContractInfoExVo;
import com.quanyan.place.entity.apiresp.RespPlaceContractInfoVo;
import com.quanyan.place.entity.apiresp.RespPlaceInfo;
import com.quanyan.place.entity.apiresp.RespPlaceUnitSalePlanDetail;
import com.quanyan.place.entity.vo.MqPlaceGroupId;
import com.quanyan.place.entity.vo.PlaceCategoryVo;
import com.quanyan.place.entity.vo.PlaceDistribution;
import com.quanyan.place.entity.vo.PlaceFromDataVo;
import com.quanyan.place.entity.vo.PlaceInfo;
import com.quanyan.place.entity.vo.PlaceKpiInfo;
import com.quanyan.place.entity.vo.PlaceNewInfo;
import com.quanyan.place.entity.vo.PlaceSaleDistribution;
import com.quanyan.place.entity.vo.ReqPlaceSearch;
import com.quanyan.place.entity.vo.TbBizPlaceUnitVo;
import com.quanyan.place.mapper.TbBizPlaceUnitSalePlanMainMapper;
import com.quanyan.place.wrapper.PlaceWrapper;
import com.quanyan.platform.client.IPlaceDubboService;
import com.quanyan.platform.response.GatherPlaceResponse;
import com.quanyan.redisCluster.utils.RedisConstants;
import com.quanyan.redisCluster.utils.RedisKey;
import com.quanyan.search.entity.vo.PlaceIndexInfo;
import com.quanyan.search.service.PlaceSearchService;
import com.quanyan.place.service.ApiPlaceOrderService;
import com.quanyan.place.service.BaseService;
import com.quanyan.place.service.CacheService;
import com.quanyan.place.service.ContractService;
import com.quanyan.place.service.PeriodService;
import com.quanyan.place.service.PlaceBaseService;
import com.quanyan.place.service.PlaceBuyService;
import com.quanyan.place.service.PlaceInnerService;
import com.quanyan.place.service.PlaceMessageService;
import com.quanyan.place.service.PlaceOrderUtilService;
import com.quanyan.place.service.TbBusinessLogService;
import com.quanyan.search.service.impl.PlaceSearchServiceImpl;
import com.quanyan.user.response.RespPlaceVideoInfo;
import com.quanyan.user.serviceFacade.VideoServiceFacade;

/**
 * 场馆wrapper实现
 * Created by yangyun on 16-6-6.
 */
@Service("placeWrapper")
public class PlaceWrapperImpl implements PlaceWrapper {

	@Autowired
	PlaceInnerService placeInnerService;

	@Autowired
	PlaceBaseService placeBaseService;

	@Autowired
	PlaceBuyService placeBuyService;

	@Autowired
	BaseService baseService;

	@Autowired
	IBaseService iBaseService;

	@Autowired
	PeriodService periodService;

	@Autowired
	private CacheService cacheService;

	@Value("${place.admin.uid}")
	private Integer placeAdminUser;

	@Autowired
	MqPlaceProductWrapperImpl mqPlaceProductWrapper;

	@Autowired
	TbBusinessLogService tbBusinessLogService;

	@Autowired
	ContractService contractService;

	@Autowired
	ISearchService searchService;

	@Autowired
	PlaceMessageService placeMessageService;

	@Autowired
	TbBizPlaceUnitSalePlanMainMapper tbBizPlaceUnitSalePlanMainMapper;

	@Autowired
	PlaceOrderUtilService placeOrderUtilService;

	@Autowired
	ClubOpenService clubOpenService;

	@Autowired
	AdminUserService adminUserService;

	private Logger logger = LoggerFactory.getLogger(PlaceWrapperImpl.class);

	@Autowired
	private VideoServiceFacade videoServiceFacade;

	@Autowired
	private IPlaceDubboService iPlaceDubboService;

	@Autowired
    ApiPlaceOrderService apiPlaceOrderSerive;

	@Autowired
	PlaceRedisTemplate placeRedisTemplate;

	@Override
	public PageObj<List<PlaceNewInfo>> getPlaceList(ReqPlaceSearch reqPlaceSearch) {
		// 添加数据权限（目前只处理到城市）
		if (null != reqPlaceSearch.getUid()){
			TbAdminUser user = adminUserService.getAdminUser(reqPlaceSearch.getUid());
			if (null == user){
				return null;
			}
			if (null != user.getDeptId() && Constants.ZERO != user.getDeptId()){
				// 不是总部员工
				reqPlaceSearch.setCityId(user.getCityId());
			}
		}
		return placeInnerService.getPlaceList(reqPlaceSearch);
	}

	@Override
	public PlaceDistribution getPlaceDistribuctionGroup(Integer cityId, Integer category, Integer districtId, Integer primeType, Integer isSign) {
		return placeInnerService.getPlaceDistribuctionGroup(cityId, category, districtId, primeType, isSign);
	}

	@Override
	public PlaceKpiInfo getPlaceSignDetailData(Integer placeId) {
		return placeInnerService.getPlaceSignDetailData(placeId);
	}

	@Override
	public PlaceSaleDistribution getPlaceSaleDistribuctionGroup(Integer cityId, Integer category, Integer districtId) {
		return placeInnerService.getPlaceSaleDistribuctionGroup(cityId, category, districtId);
	}

	/**
	 * 商务场馆列表
	 *
	 * @param reqPlaceSearch
	 * @return
	 */
	@Override
	public PageObj<List<PlaceInfo>> getCommercePlaceList(ReqPlaceSearch reqPlaceSearch) {
		Integer uid = null;
		Integer pageNum = 0;
		Integer pageSize = Constants.DEFAULT_PAGE_SIZE;
		String keywords = "";
		if (null != reqPlaceSearch) {
			uid = reqPlaceSearch.getUid();
			pageNum = reqPlaceSearch.getPageNum();
			pageSize = reqPlaceSearch.getPageSize();
			keywords = reqPlaceSearch.getKey();
		}

		int totalNum = placeInnerService.countCommercePlace(uid, keywords);
		List<PlaceInfo> placeInfoList = new ArrayList<PlaceInfo>();
		if (null != uid) {
			List<TbBizPlace> placeList = placeInnerService.getCommercePlaceList(uid, pageNum, pageSize, keywords);
			for (TbBizPlace place : placeList) {
				PlaceInfo placeInfo = new PlaceInfo();
				placeInfo.setPlaceMain(place);
				placeInfoList.add(placeInfo);
			}
		}
		PageObj<List<PlaceInfo>> result = PageObj.create(totalNum, pageNum, pageSize, placeInfoList);

		return result;
	}

	/**
	 * 录入场馆信息
	 *
	 * @param placeFromDataVo
	 * @return
	 */
	@Override
	public APIResponse saveOrUpdatePlace(PlaceFromDataVo placeFromDataVo) {
		// 校验场馆信息
		APIResponse retValidate = placeInnerService.validatePlaceData(placeFromDataVo);
		if (null != retValidate) {
			return retValidate;
		}
		// 校验场地信息
		if (null != placeFromDataVo.getPlace_unit_list() && placeFromDataVo.getPlace_unit_list().size() > 0) {
			retValidate = placeInnerService.validatePlaceUnitData(placeFromDataVo.getPlace_unit_list());
		}
		if (null != retValidate) {
			return retValidate;
		}
		TbBizPlace tbBizPlace = placeInnerService.savePlaceInfo(placeFromDataVo);

		TbCity city = baseService.getCityById(tbBizPlace.getCityId());
		// 场馆经营范围
		PlaceCategoryVo placeCategory = placeInnerService.getPlaceCategory(tbBizPlace.getId());
		// 生成场馆编号
		String placeCode = placeBaseService.generatePlaceCode(city.getPinyin(), tbBizPlace.getId(), placeCategory.getCategoryIdSet());
		tbBizPlace.setCode(placeCode);
		placeBaseService.updatePlaceBySelective(tbBizPlace);

		//插入默认场馆锁定周期，解锁周期
		periodService.importPeriodData(tbBizPlace.getId());

		//加入消息队列进行异步处理
		MqPlaceGroupId mqPlaceGroupId = new MqPlaceGroupId();
		mqPlaceGroupId.setId(tbBizPlace.getId());
		mqPlaceGroupId.setName(tbBizPlace.getName());
		mqPlaceGroupId.setUid(placeAdminUser);
		mqPlaceGroupId.setHead(tbBizPlace.getBizPlaceUrl());
		Integer result = placeInnerService.updatePlaceGroupId(mqPlaceGroupId);
		if (result < 0) {
			//异常时加入消息队列处理，更新群id,以及更新索引
			mqPlaceProductWrapper.updatePlaceGroupIdAsyncSend(mqPlaceGroupId);
		}

		try {
			this.searchService.addPlaceIndex(tbBizPlace, null);
		} catch (Exception e) {
			logger.error("更新场馆索引失败:{}", e.getMessage());
		}

		return APIResponse.returnSuccess(tbBizPlace.getId());
	}

	/**
	 * 录入场地数据
	 *
	 * @param placeFromDataVo
	 * @return
	 */
	@Override
	@Transactional
	public APIResponse savePlaceUnitData(PlaceFromDataVo placeFromDataVo) {
		List<TbBizPlaceUnitVo> bizPlaceUnitVoList = placeFromDataVo.getPlace_unit_list();
		if (bizPlaceUnitVoList == null || bizPlaceUnitVoList.size() == 0) {
			return APIResponse.returnFail("场地为空！");
		}
		// 校验场地信息
		APIResponse apiResponse = placeInnerService.validatePlaceUnitData(bizPlaceUnitVoList);
		if (apiResponse != null) {
			return apiResponse;
		}
		return placeInnerService.importPlaceUnitData(placeFromDataVo.getPlaceId(), bizPlaceUnitVoList);
	}

	/**
	 * 更新场馆信息
	 *
	 * @param placeFromDataVo
	 * @return
	 */
	@Override
	@Transactional
	public APIResponse updatePlaceData(PlaceFromDataVo placeFromDataVo) {
		if (null == placeFromDataVo){
			return APIResponse.returnFail("参数错误");
		}
		Integer placeId = placeFromDataVo.getId();
		TbBizPlace tbBizPlace = placeBaseService.getPlaceById(placeId);

		boolean isCodeNeedsChanged = false; // 场馆编号是否需要变更
		if (null != placeFromDataVo.getPlaceCategoryList()){
			// 更新场馆经营类型
			Set<Integer> selectedCategorySet = new HashSet(placeFromDataVo.getPlaceCategoryList());
			isCodeNeedsChanged = this.updatePlaceCategory(selectedCategorySet, placeFromDataVo.getId());
			if (null != tbBizPlace &&
					null != placeFromDataVo.getCityId() &&
					!tbBizPlace.getCityId().equals(placeFromDataVo.getCityId())){
				isCodeNeedsChanged = true;
			}
			if (isCodeNeedsChanged) {
				TbCity city = baseService.getCityById(placeFromDataVo.getCityId());
				// 场馆编号
				String placeCode = placeBaseService.generatePlaceCode(city.getPinyin(), placeId, selectedCategorySet);
				placeFromDataVo.setCode(placeCode);
			}
		}
		APIResponse result = placeInnerService.updatePlaceData(placeFromDataVo);
		if (result.isRet()) {
			placeInnerService.updatePlaceImageAndVideo(placeFromDataVo, placeId); // 更新图片，视频
			//修改场馆订单运营方式
			placeOrderUtilService.updatePlaceOrderBusinessMode(placeId, placeFromDataVo.getBusinessMode());

			try {
				this.searchService.addPlaceIndex(tbBizPlace, null);
			} catch (Exception e) {
				logger.error("更新场馆索引失败:{}", e.getMessage());
			}
		}
		return result;
	}

	/**
	 * 更新场馆经营类型
	 * @param selectedCategorySet 前端传递场馆项目
	 * @param placeId
     * @return
     */
	private boolean updatePlaceCategory(Set<Integer> selectedCategorySet, Integer placeId) {
		boolean isCodeNeedsChanged = false;
		Set<Integer> alreadyExistsCategorySet = new HashSet<Integer>();
		List<TbBizPlaceCategory> dbPlaceCategoryList = placeBaseService.getPlaceCategoryList(placeId);
		for (TbBizPlaceCategory categroy : dbPlaceCategoryList) {
			alreadyExistsCategorySet.add(categroy.getCategoryId());
			if (!selectedCategorySet.contains(categroy.getCategoryId())) {
				isCodeNeedsChanged = true;
				// 原来已经存在，现在要取消的部分
				placeBaseService.deletePlaceCategory(categroy.getId());
			}
		}
		// 求差集
		Set<Integer> subTractSet = new HashSet<Integer>();
		subTractSet.addAll(selectedCategorySet);
		subTractSet.removeAll(alreadyExistsCategorySet);
		if (null != selectedCategorySet) {
			if (subTractSet.size() > 0) {
				isCodeNeedsChanged = true;
				for (Integer categoryId : subTractSet) {
					TbBizPlaceCategory tbBizPlaceCategory = new TbBizPlaceCategory();
					tbBizPlaceCategory.setPlaceId(placeId);
					tbBizPlaceCategory.setCategoryId(categoryId);
					placeBaseService.insertPlaceCategory(tbBizPlaceCategory);
				}
			}
		}
		return isCodeNeedsChanged;
	}


	/**
	 * 删除场馆
	 *
	 * @param placeId
	 * @return
	 */
	@Override
	@Transactional
	public APIResponse deletePlace(Integer placeId) {
		if (!placeBuyService.isDeletePlace(placeId, 1)) {
			return APIResponse.returnFail("场馆签约还在合同期内，删除失败。");
		} else {
			APIResponse result = placeInnerService.deletePlace(placeId);
			// 删除场馆后将所有该场馆下的销售计划置为无效
			placeInnerService.updateSalePlanToInvalidate(placeId, Constants.BYTE_ONE);
			//将销售计划模板置为无效
			TbBizPlaceUnitSalePlanMainExample placeUnitSalePlanMainExample = new TbBizPlaceUnitSalePlanMainExample();
			TbBizPlaceUnitSalePlanMainExample.Criteria criteria = placeUnitSalePlanMainExample.createCriteria();
			criteria.andPlaceIdEqualTo(placeId);
			TbBizPlaceUnitSalePlanMain tbBizPlaceUnitSalePlanMain = new TbBizPlaceUnitSalePlanMain();
			tbBizPlaceUnitSalePlanMain.setIsEffective(PlaceConstants.IS_EFFECTIVE_NO);
			tbBizPlaceUnitSalePlanMainMapper.updateByExampleSelective(tbBizPlaceUnitSalePlanMain, placeUnitSalePlanMainExample);

			return result;
		}
	}

	/**
	 * 删除场馆单元（场地）
	 *
	 * @param placeUnitId
	 * @return
	 */
	@Override
	@Transactional
	public APIResponse deletePlaceUnit(Integer placeUnitId) {
		if (!placeBuyService.isDeletePlace(placeUnitId, 2)) {
			return APIResponse.returnFail("场地签约还在合同期内，删除失败。");
		} else {
			APIResponse result = placeInnerService.deletePlaceUnit(placeUnitId);
			// 删除场地单元后将所有该场地下的销售计划置为无效
			placeInnerService.updateSalePlanToInvalidate(placeUnitId, Constants.BYTE_TWO);
			//将销售计划模板置为无效
			TbBizPlaceUnitSalePlanMainExample placeUnitSalePlanMainExample = new TbBizPlaceUnitSalePlanMainExample();
			TbBizPlaceUnitSalePlanMainExample.Criteria criteria = placeUnitSalePlanMainExample.createCriteria();
			criteria.andPlaceUnitIdEqualTo(placeUnitId);
			TbBizPlaceUnitSalePlanMain tbBizPlaceUnitSalePlanMain = new TbBizPlaceUnitSalePlanMain();
			tbBizPlaceUnitSalePlanMain.setIsEffective(PlaceConstants.IS_EFFECTIVE_NO);
			tbBizPlaceUnitSalePlanMainMapper.updateByExampleSelective(tbBizPlaceUnitSalePlanMain, placeUnitSalePlanMainExample);

			return result;
		}
	}

	/**
	 * solr导入场馆索引
	 *
	 * @param map
	 * @param solrUrl
	 * @return
	 */
	public String importIndex(Map map, String solrUrl) {
		try {
			PlaceSearchService placeSearchService = new PlaceSearchServiceImpl(solrUrl);

			List<PlaceIndexInfo> inserPlaceIndexInfos = new ArrayList<>();
			List<TbBizPlace> placeList = placeInnerService.getPlaceListForSolrIndex(map);
			if (CollectionUtils.isNotEmpty(placeList)) {
				for (TbBizPlace tbBizPlace : placeList) {

					PlaceIndexInfo placeIndexInfo = iBaseService.tb2InsertPlaceIndexInfo(tbBizPlace);

					List<PlaceIndexInfo> placeIndexInfos = iBaseService.getPlaceSalePlanSerach(tbBizPlace,
							MapUtils.getInteger(map, "days"), placeIndexInfo);
					if (CollectionUtils.isNotEmpty(placeIndexInfos)) {
						inserPlaceIndexInfos.addAll(placeIndexInfos);
					}
				}
				APIResponse response = placeSearchService.insertDocs(inserPlaceIndexInfos);
				if (response.isRet()) {
					return "导入场馆索引成功";
				} else {
					return "导入场馆索引失败:" + response.getErrmsg();
				}
			}

			return "没有要导入的场馆索引";
		} catch (Exception e) {
			e.printStackTrace();
			return "导入场馆索引失败:" + e.getMessage();
		}
	}

	@Override
	public APIResponse updatePlaceGroupId(ReqPlaceInfo reqPlaceInfo) {
		if (reqPlaceInfo != null && reqPlaceInfo.getPlaceIdList().size() > 0) {
			List<Integer> placeIdList = reqPlaceInfo.getPlaceIdList();
			for (Integer integer : placeIdList) {
				APIResponse apiResponse = placeInnerService.getPlaceData(integer);
				TbBizPlace tbBizPlace = (TbBizPlace) apiResponse.getData();
				try {
					MqPlaceGroupId mqPlaceGroupId = new MqPlaceGroupId();
					mqPlaceGroupId.setId(tbBizPlace.getId());
					mqPlaceGroupId.setName(tbBizPlace.getName());
					mqPlaceGroupId.setUid(placeAdminUser);
					if (reqPlaceInfo.getUid() != null && reqPlaceInfo.getUid() > 0) {
						mqPlaceGroupId.setUid(reqPlaceInfo.getUid());
					}
					mqPlaceGroupId.setHead(tbBizPlace.getBizPlaceUrl());
					//mq异步处理
					if (reqPlaceInfo.getType() != null && reqPlaceInfo.getType().equals(2)) {
						mqPlaceProductWrapper.updatePlaceGroupIdAsyncSend(mqPlaceGroupId);
					} else {
						placeInnerService.updatePlaceGroupId(mqPlaceGroupId);
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} else {
			Map<String, Object> map = new HashMap<>();
			Integer size = 100;
			if (reqPlaceInfo.getSize() == null) {
				reqPlaceInfo.setSize(size);
			}
			map.put("size", reqPlaceInfo.getSize());
			List<TbBizPlace> tbBizPlaceList = placeInnerService.getPlaceList(map);
			for (TbBizPlace tbBizPlace : tbBizPlaceList) {
				try {
					MqPlaceGroupId mqPlaceGroupId = new MqPlaceGroupId();
					mqPlaceGroupId.setId(tbBizPlace.getId());
					mqPlaceGroupId.setName(tbBizPlace.getName());
					mqPlaceGroupId.setUid(placeAdminUser);
					if (reqPlaceInfo.getUid() != null && reqPlaceInfo.getUid() > 0) {
						mqPlaceGroupId.setUid(reqPlaceInfo.getUid());
					}
					mqPlaceGroupId.setHead(tbBizPlace.getBizPlaceUrl());
					//mq异步处理
					if (reqPlaceInfo.getType() != null && reqPlaceInfo.getType().equals(2)) {
						mqPlaceProductWrapper.updatePlaceGroupIdAsyncSend(mqPlaceGroupId);
					} else {
						placeInnerService.updatePlaceGroupId(mqPlaceGroupId);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return APIResponse.returnSuccess();
	}

	/**
	 * 合同列表
	 *
	 * @param vo
	 * @return
	 */

	@Override
	public PageObj<List<RespPlaceContractInfoVo>> getContractList(ReqPlaceContractInfoVo vo) {
		return contractService.getContractList(vo);
	}

	@Override
	public PageObj<List<RespPlaceContractInfoExVo>> getContractListEx(ReqPlaceContractInfoVo reqVo) {
		Map<Integer, PlaceFromDataVo> placeMap = new HashMap<>();

		// 筛选合同列表
		List<RespPlaceContractInfoExVo> contractExs = new ArrayList<>();
		PageObj<List<RespPlaceContractInfoVo>> pagedContracts = getContractList(reqVo);
		List<RespPlaceContractInfoVo> contractLites = pagedContracts.getItems();
		if (contractLites != null) {
			for (RespPlaceContractInfoVo contract : contractLites) {
				try {
					Integer cid = contract.getId();
					//RespPlaceContractInfoVo cvo = getContractDataById(cid);
					RespPlaceContractInfoVo cvo = contract;
					if (cvo == null) {
						continue;
					}
					RespPlaceContractInfoExVo contractEx = new RespPlaceContractInfoExVo();

					List<TbBizPlaceBuyContractDetail> tbDetails = contractService.getContractDetailByContractId(cvo.getId());
					if (tbDetails != null && tbDetails.size() > 0) {
						PlaceBuyContractDetail placeBuyContractDetail;
						List<PlaceBuyContractDetail> details = new ArrayList<>();
						for (TbBizPlaceBuyContractDetail tbBizPlaceBuyContractDetail : tbDetails) {
							placeBuyContractDetail = newPlaceBuyContractDetailFromTbDetail(tbBizPlaceBuyContractDetail);
							details.add(placeBuyContractDetail);
						}
						cvo.setContractDetails(details);
					}
					contractEx.setContractInfo(cvo);

					// 获取场馆数据
					Integer pid = cvo.getPlaceId();
					if (!placeMap.containsKey(pid)) {
						APIResponse result = placeInnerService.getPlaceDetailData(cvo.getPlaceId().intValue());
						if (result.isRet()) {
							PlaceFromDataVo pi = (PlaceFromDataVo) result.getData();
							if (pi != null) {
								placeMap.put(pid, pi);
							}
						}
					}
					contractEx.setPlaceInfo(placeMap.get(pid));

					contractExs.add(contractEx);
				} catch (Exception ex) {
					ex.printStackTrace();
					continue;
				}
			}
		}

		PageObj<List<RespPlaceContractInfoExVo>> result = PageObj.create(
				pagedContracts.getTotal(), pagedContracts.getPageNum(), pagedContracts.getSize(), contractExs);
		return result;
	}

	/**
	 * 根据合同Id获取合同详情
	 *
	 * @param contractId
	 * @return
	 */
	@Override
	public RespPlaceContractInfoVo getContractDataById(Integer contractId) {
		RespPlaceContractInfoVo respVo = new RespPlaceContractInfoVo();
		TbBizPlaceBuyContract vo = contractService.getContractInfoById(contractId);
		List<TbBizPlaceBuyContractDetail> detailVoList = contractService.getPlaceIdAndUnitIdByContractId(contractId);
		List<TbBizPlaceUnit> unitList = new ArrayList<TbBizPlaceUnit>();
		if (vo != null) {
			if (vo.getPlaceId() != null) {
				TbBizPlace placeVo = placeBaseService.getPlaceById(vo.getPlaceId());
				if (placeVo != null) {
					respVo.setPlaceName(placeVo.getName());
					respVo.setCode(placeVo.getCode());
				}
			}
		}
		if (detailVoList != null && detailVoList.size() > 0) {
			respVo.setFinishDate(detailVoList.get(0).getFinishDate());
			for (TbBizPlaceBuyContractDetail detailVo : detailVoList)
				if (detailVo.getPlaceId() != null && detailVo.getPlaceUnitId() != null && detailVo.getPlaceUnitId() > 0) {
					//获得场地信息
					APIResponse<List<TbBizPlaceUnit>> placeUnitResult = placeInnerService.getPlaceUnitData(detailVo.getPlaceId(), detailVo.getPlaceUnitId());
					if (placeUnitResult.isRet()) {
						if (placeUnitResult.getData() != null && placeUnitResult.getData().size() > 0) {
							TbBizPlaceUnit voVal = placeUnitResult.getData().get(0);
							unitList.add(voVal);
						}

					}
				}
		}

		List<TbBizPlaceBuyContractDetail> listVal = contractService.getContractDetailByContractId(contractId);
		if (listVal != null && listVal.size() > 0) {
			respVo.setFinishDate(listVal.get(0).getFinishDate());
		}

		respVo.setId(vo.getId());
		respVo.setContractNo(vo.getContractNo());
		respVo.setBuyType(vo.getBuyType());
		if (PlaceConstants.BUY_TYPE_TIME.equals(vo.getBuyType())) {
			respVo.setTypeName("时段买入");
		} else if (PlaceConstants.BUY_TYPE_WHOLE.equals(vo.getBuyType())) {
			respVo.setTypeName("整馆买入");
		} else if (PlaceConstants.BUY_TYPE_GROUP.equals(vo.getBuyType())) {
			respVo.setTypeName("包片买入");
		} else if (PlaceConstants.BUY_TYPE_TRUE_TIME.equals(vo.getBuyType())) {
			respVo.setTypeName("真包时");
		} else if (PlaceConstants.BUY_TYPE_FALSE_TIME.equals(vo.getBuyType())) {
			respVo.setTypeName("假包时");
		}
		respVo.setBuyDate(vo.getBuyDate());
		//合同状态 1，未执行 ， 2 已执行，3 已中止，4  已结束 5 已废弃
		if (PlaceConstants.PLACE_CONTRACT_UNEXECUTED.equals(vo.getStatus())) {
			respVo.setStatusName("未执行");
		} else if (PlaceConstants.PLACE_CONTRACT_EXECUTED.equals(vo.getStatus())) {
			respVo.setStatusName("已执行");
		} else if (PlaceConstants.PLACE_CONTRACT_STOP.equals(vo.getStatus())) {
			respVo.setStatusName("已中止");
		} else if (PlaceConstants.PLACE_CONTRACT_END.equals(vo.getStatus())) {
			respVo.setStatusName("已结束");
		} else if (PlaceConstants.PLACE_CONTRACT_DELETE.equals(vo.getStatus())) {
			respVo.setStatusName("已废弃");
		} else {
			respVo.setStatusName("");
		}
		respVo.setStatus(vo.getStatus());
		respVo.setTotalPrice(vo.getTotalPrice());
		respVo.setBillingCycle(vo.getBillingCycle());
		respVo.setSignPeople(vo.getSignPeople());
		respVo.setSignDate(vo.getSignDate());
		respVo.setPhone(vo.getPhone());
		respVo.setRemark(vo.getRemark());
		respVo.setPlaceUnitlist(unitList);
		respVo.setStopReason(vo.getStopReason());
		respVo.setDeleteReason(vo.getDeleteReason());
		respVo.setContractNo(vo.getContractNo());
		respVo.setStopReason(vo.getStopReason());
		respVo.setDeleteReason(vo.getDeleteReason());

		// 新添加的字段要加入
		respVo.setReceiveCompanyName(vo.getReceiveCompanyName());
		respVo.setTaxRate(vo.getTaxRate());
		respVo.setInvoice(vo.getInvoice());
		respVo.setAccountWay(vo.getAccountWay());
		respVo.setCalRentStartTime(vo.getCalRentStartTime());
		respVo.setCalRentEndTime(vo.getCalRentEndTime());

		return respVo;
	}

	/**
	 * 根据合同编号 场地ID拿到合同详情
	 *
	 * @param placeUnitId
	 * @param attractId
	 * @return
	 */
	@Override
	public List<PlaceBuyContractDetail> getPlaceBuyContractDetailByPlaceUnitId(Integer placeUnitId, Integer attractId) {
		return placeBuyService.getPlaceBuyContractDetailByPlaceUnitId(placeUnitId, attractId);
	}

	/**
	 * 根据类别ID(足,篮,网,羽)拿到场馆信息
	 *
	 * @param reqVo
	 * @return
	 */
	@Override
	public PageObj<List<RespPlaceInfo>> getPlaceListByCategoryId(ReqPlaceSearch reqVo) {
		return placeInnerService.getPlaceListByCategoryId(reqVo);
	}

	/**
	 * 更新合同
	 *
	 * @param reqVo
	 * @return
	 */
	@Override
	public APIResponse updatePlaceContratctInfo(ReqPlaceContractInfoVo reqVo) {
		// 判断合同内容是否有变化，此处需要增加对详情是否修改的判断[暂时所有更新都接受]
		if (compareUpdateContranct(reqVo) || true) {
			APIResponse result = contractService.updatePlaceContratctInfo(reqVo);
			if (result.getErrcode() == 100) {
				String errmsg1 = result.getErrmsg();
				return APIResponse.returnFail(errmsg1);
			}

			// 需要按时段来修改
			APIResponse result2 = contractService.updatePlaceContratctDetailInfo(reqVo);
			if (result2.getErrcode() == 100) {
				String errmsg2 = result.getErrmsg();
				return APIResponse.returnFail(errmsg2);
			}

			// 设置合同状态为未审核
			contractService.setVerifyFlag(reqVo.getId(), PlaceConstants.PLACE_CONTRACT_VERIFY_NO);

			//日志记录
			tbBusinessLogService.insertIntoBusinessLog(reqVo.getId(), PlaceConstants.LOG_TYPE_PLACE_CONTRACT, reqVo.getUid(), "合同变更", "修改合同");
		}
		return APIResponse.returnSuccess();
	}

	public boolean compareUpdateContranct(ReqPlaceContractInfoVo reqVo) {
		SimpleDateFormat smf = new SimpleDateFormat("yyyy-MM-dd");
		Integer buyType = null;
		String buyDate = null;
		BigDecimal totalPrice = null;
		String signPeople = null;
		String signDate = null;
		String remark = null;
		Integer billingCycle = null;
		String finishDate = null;
		boolean flag = false;
		String contractNo = null;
		String phone = null;

		boolean buyDateBoolean = false;
		boolean totalPriceBoolean = false;
		boolean signPeopleBoolean = false;
		boolean signDateBoolean = false;
		boolean remarkBoolean = false;
		boolean billingCycleBoolean = false;
		boolean finishDateBoolean = false;
		boolean contractNoBoolean = false;
		boolean phoneBoolean = false;

		TbBizPlaceBuyContract vo = contractService.getContractInfoById(reqVo.getId());
		List<TbBizPlaceBuyContractDetail> detailV0 = contractService.getContractDetailByContractId(reqVo.getId());
		if (detailV0 != null && detailV0.size() > 0) {
			finishDate = smf.format(detailV0.get(0).getFinishDate());
		}
		if (vo != null) {
			buyType = vo.getBuyType();
			if (vo.getBuyDate() != null) {
				buyDate = smf.format(vo.getBuyDate());
			}
			totalPrice = vo.getTotalPrice();
			signPeople = vo.getSignPeople();
			if (vo.getSignDate() != null) {
				signDate = smf.format(vo.getSignDate());
			}
			remark = vo.getRemark();
			billingCycle = vo.getBillingCycle();
			contractNo = vo.getContractNo();
			phone = vo.getPhone();
		}
		int value = totalPrice.compareTo(reqVo.getTotalPrice());
		if (value == 0) {
			flag = true;
		}

		if (contractNo != null) {
			if (reqVo.getContractNo() != null) {
				if (contractNo.equals(reqVo.getContractNo())) {
					contractNoBoolean = true;
				}
			}
		}

		if (remark != null) {
			if (reqVo.getRemark() != null) {
				if (remark.equals(reqVo.getRemark())) {
					remarkBoolean = true;
				}
			}
		}
		if (buyDate != null) {
			if (reqVo.getBuyDate() != null) {
				if (buyDate.equals(smf.format(reqVo.getBuyDate()))) {
					buyDateBoolean = true;
				}
			}
		}
		if (signPeople != null) {
			if (reqVo.getSignPeople() != null) {
				if (signPeople.equals(reqVo.getSignPeople())) {
					signPeopleBoolean = true;
				}
			}
		}

		if (signDate != null) {
			if (reqVo.getSignDate() != null) {
				if (signDate.equals(smf.format(reqVo.getSignDate()))) {
					signDateBoolean = true;
				}
			}
		}

		if (finishDate != null) {
			if (reqVo.getFinishDate() != null) {
				if (finishDate.equals(smf.format(reqVo.getFinishDate()))) {
					finishDateBoolean = true;
				}
			}
		}

		if (billingCycle != null) {
			if (reqVo.getBillingCycle() != null) {
				if (billingCycle.equals(reqVo.getBillingCycle())) {
					billingCycleBoolean = true;
				}
			}
		}
		if (phone != null) {
			if (reqVo.getPhone() != null) {
				if (phone.equals(reqVo.getPhone())) {
					phoneBoolean = true;
				}
			}
		}
/*
        if (signPeople.equals(reqVo.getSignPeople())){
            System.out.print("3");
        }
        if (signDate.equals(smf.format(reqVo.getSignDate()))){
            System.out.print("4");
        }
        if (buyDate.equals(smf.format(reqVo.getBuyDate()))){
            System.out.print("5");
        }
        if (finishDate.equals(smf.format(reqVo.getFinishDate()))){
            System.out.print("6");
        }
        if (billingCycle.equals(reqVo.getBillingCycle())){
            System.out.print("7");
        }
*/

         /*
            if (flag){
                System.out.print("2");
            }
            */

        if (reqVo.getBillingCycle() == null) {
            if (!(contractNoBoolean &&buyDateBoolean && flag && signPeopleBoolean && signDateBoolean && finishDateBoolean &&remarkBoolean && phoneBoolean)) {
                return true;
            }
        }else {
            if (!(contractNoBoolean && buyDateBoolean && flag && signPeopleBoolean && signDateBoolean && finishDateBoolean && billingCycleBoolean && remarkBoolean &&phoneBoolean)) {
                return true;
            }
        }
        return false;
        }

    public boolean compareStopContranct(ReqPlaceContractInfoVo reqVo){
        String reason = null;
        TbBizPlaceBuyContract vo = contractService.getContractInfoById(reqVo.getId());
        if (vo != null) {
            reason=vo.getStopReason();
        }
        if (reqVo.getStopReason()!=null) {
            if (reqVo.getStopReason().equals(reason)){
                return false;
            }else{
                return true;
            }
        }
        return false;
    }
  

    // 将当前合同导入到历史表中
    public void importContractIntoHistory(Integer id) {
        // 在合同历史中将该合同的历史版本全部清除
        contractService.ClearContractHistory(id);

        // 重置合同初始版本号
        String versionKey = "Contract_verison_" + id.toString();
        cacheService.resetRunningNumber(versionKey, "");

        // 添加第一版合同
        long version = cacheService.getRunningNumber(versionKey, "");
        if (version == 1) {
            // 备份合同内容
            contractService.BackupContractHistory(id, (int) version);
        }
    }

    @Override
    public APIResponse verifyContratctInfo(ReqPlaceContractInfoVo reqVo) {
        // 读取合同信息,确保合同必须字段有效
        APIResponse checkResult = contractService.CheckContractForVerify(reqVo.getId());
        if (!checkResult.isRet()) {
            return checkResult;
        }

        String versionKey = "Contract_verison_" + reqVo.getId().toString();

        long nextVersion = cacheService.getRunningNumber(versionKey, "");

        // 修改上一版本合同的的执行区间
        if (nextVersion > 1) {
            long lastVersion = nextVersion - 1;
            contractService.UpdateContractExecuteTime(reqVo.getId(), (int) lastVersion);
        }

        // 备份新版本的合同
        contractService.BackupContractHistory(reqVo.getId(), (int) nextVersion);

        // 修改合同的审核状态为已审核
        return contractService.verifyContratctInfo(reqVo);
    }
   

	@Override
	public int getPlaceActivityStatus(Integer placeId) {
		List<Integer> placeIds =Arrays.asList(placeId);
        Integer pageNum = 1;
        Integer pageSize = 100;
        // 视频 < 俱乐部 < 俱乐部活动 < 达人活动    按照执行耗时由快到慢依次获取
        try {
        	APIResponse<List<RespPlaceVideoInfo>> response = videoServiceFacade.getPlaceVideosByPlaceId(placeId, pageSize);
            if (null != response && null != response.getData() && response.getData().size() > 0){
            	return 1;
              }
            } catch (Exception e) {
            	logger.error("获取场馆关联视频异常:{}", e);
            }
        
        try {
        	 Map<Integer, List<RespPlaceClubInfo>> clubMap = 
        			 clubOpenService.selectClubByPlaceIds(placeIds, pageNum, pageSize, 0);//0 表示查询所有栏目
             if (null != clubMap && clubMap.size() > 0 && !CollectionUtils.isEmpty(clubMap.get(placeId))){
             	return 1;
             }
             } catch (Exception e) {
            	logger.error("获取场馆关联俱乐部异常:{}", e);
             }
            
        try {
        	 Map<Integer, List<RespPlaceClubInfo>> activityMap = 
        			 clubOpenService.selectActivityByPlaceIds(placeIds, pageNum, pageSize, 0);//0 表示查询所有栏目
             if (null != activityMap && activityMap.size() > 0 && !CollectionUtils.isEmpty(activityMap.get(placeId))){
             	return 1;
              }
            } catch (Exception e) {
           	   logger.error("获取场馆关联俱乐部活动异常:{}", e);
            }
            
        try {
        	 List<GatherPlaceResponse> gatherList = iPlaceDubboService.getGatherPlaceInfo(placeIds, pageNum-1, pageSize);
             if (null != gatherList && gatherList.size() > 0){
             	return 1;
             }
           } catch (Exception e) {
          	   logger.error("获取场馆关联达人信息异常:{}", e);
           }
		return 0;
	}


	public boolean compareDeleteContranct(ReqPlaceContractInfoVo reqVo) {
		String deleteReason = null;
		TbBizPlaceBuyContract vo = contractService.getContractInfoById(reqVo.getId());
		if (vo != null) {
			deleteReason = vo.getDeleteReason();
		}
		if (reqVo.getDeleteReason() != null) {
			if (reqVo.getDeleteReason().equals(deleteReason)) {
				return false;
			} else {
				return true;
			}
		}
		return false;
	}

	/**
	 * 废弃合同
	 *
	 * @param reqVo
	 * @return
	 */
	@Override
	@Transactional
	public APIResponse deletePlaceContratctInfo(ReqPlaceContractInfoVo reqVo) {
		contractService.deletePlaceContratctInfo(reqVo);
		contractService.deletePlaceContratctDetailInfo(reqVo);
		List<TbBizPlaceBuyContractDetail> detailVoList = contractService.getPlaceIdAndUnitIdByContractId(reqVo.getId());
		//将场地改成未签约
		for (TbBizPlaceBuyContractDetail vo : detailVoList) {
			TbBizPlaceUnit unitVo = new TbBizPlaceUnit();
			unitVo.setId(vo.getPlaceUnitId());
			unitVo.setIsSign(PlaceConstants.IS_SIGN_NO);
			placeBaseService.updatePlaceUnitBySelective(unitVo);
			// 删除场地单元后将所有该场地下的销售计划置为无效
			placeInnerService.updateSalePlanToInvalidate(vo.getPlaceUnitId(), Constants.BYTE_TWO);
		}
		if (contractService.getContractListByPlaceId(reqVo).size() == 0) {
			//修改场馆签约状态
			TbBizPlace vo = new TbBizPlace();
			vo.setIsSign(PlaceConstants.IS_SIGN_NO);
			vo.setIsShelves(Constants.ZERO); //  已下架
			vo.setId(reqVo.getPlaceId());
			placeBaseService.updatePlaceBySelective(vo);
			// 将所有该场馆下的销售计划置为无效
			placeInnerService.updateSalePlanToInvalidate(reqVo.getPlaceId(), Constants.BYTE_ONE);
		}
		//签约时段  将销售计划模板置为无效
		for (TbBizPlaceBuyContractDetail detailVo : detailVoList) {
			TbBizPlaceUnitSalePlanMainExample placeUnitSalePlanMainExample = new TbBizPlaceUnitSalePlanMainExample();
			TbBizPlaceUnitSalePlanMainExample.Criteria criteria = placeUnitSalePlanMainExample.createCriteria();
			criteria.andPlaceIdEqualTo(detailVo.getPlaceId());
			criteria.andPlaceUnitIdEqualTo(detailVo.getPlaceUnitId());
			if (detailVo.getBuyStartTime() != null) {
				criteria.andStartTimeEqualTo(detailVo.getBuyStartTime());
			}
			if (detailVo.getBuyEndTime() != null) {
				criteria.andEndTimeEqualTo(detailVo.getBuyEndTime());
			}
			TbBizPlaceUnitSalePlanMain tbBizPlaceUnitSalePlanMain = new TbBizPlaceUnitSalePlanMain();
			tbBizPlaceUnitSalePlanMain.setIsEffective(PlaceConstants.IS_EFFECTIVE_NO);
			tbBizPlaceUnitSalePlanMainMapper.updateByExampleSelective(tbBizPlaceUnitSalePlanMain, placeUnitSalePlanMainExample);
		}
		updateSolrIndex(reqVo.getPlaceId());
		//日志记录
		tbBusinessLogService.insertIntoBusinessLog(reqVo.getId(), PlaceConstants.LOG_TYPE_PLACE_CONTRACT, reqVo.getUid(), "合同废弃", "废弃合同");
		return APIResponse.returnSuccess();
	}


	public void delSolrSaleIndex(Integer placeId) {
		searchService.deleteDocById(placeId, PlaceConstants.SOLR_INDEX_PLAN);
	}

	public void delSolrPlaceIndex(Integer placeId) {
		searchService.deleteDocById(placeId, PlaceConstants.SOLR_INDEX_PLACE);
	}


	/**
	 * 场馆上下架操作
	 *
	 * @param placeId
	 * @param status
	 * @return
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public APIResponse isShelves(Integer placeId, Integer status) {
		TbBizPlace tbBizPlace = new TbBizPlace();
		tbBizPlace.setId(placeId);
		tbBizPlace.setIsShelves(status);
		boolean flag = placeBaseService.updateByPrimaryKeySelective(tbBizPlace);
		if (flag) {
			return APIResponse.returnSuccess();
		}
		return APIResponse.returnSuccess(false);
	}

	/**
	 * 终止合同
	 *
	 * @param reqVo
	 * @return
	 */
	@Override
	public APIResponse stopPlaceContratct(ReqPlaceContractInfoVo reqVo) {
		contractService.stopPlaceContratct(reqVo);
		contractService.deletePlaceContratctDetailInfo(reqVo);
		List<TbBizPlaceBuyContractDetail> detailVoList = contractService.getPlaceIdAndUnitIdByContractId(reqVo.getId());
		//将场地改成未签约
		for (TbBizPlaceBuyContractDetail vo : detailVoList) {
			TbBizPlaceUnit unitVo = new TbBizPlaceUnit();
			unitVo.setId(vo.getPlaceUnitId());
			unitVo.setIsSign(PlaceConstants.IS_SIGN_NO);
			placeBaseService.updatePlaceUnitBySelective(unitVo);
			// 删除场地单元后将所有该场地下的销售计划置为无效
			placeInnerService.updateSalePlanToInvalidate(vo.getPlaceUnitId(), Constants.BYTE_TWO);
		}
		if (contractService.getContractListByPlaceId(reqVo).size() == 0) {
			//修改场馆签约状态
			TbBizPlace vo = new TbBizPlace();
			vo.setIsSign(PlaceConstants.IS_SIGN_NO);
			vo.setIsShelves(Constants.ZERO); //  已下架
			vo.setId(reqVo.getPlaceId());
			placeBaseService.updatePlaceBySelective(vo);
			// 将所有该场馆下的销售计划置为无效
			placeInnerService.updateSalePlanToInvalidate(reqVo.getPlaceId(), Constants.BYTE_ONE);
			//日志记录
			tbBusinessLogService.insertIntoBusinessLog(reqVo.getId(), PlaceConstants.LOG_TYPE_PLACE_CONTRACT, reqVo.getUid(), "合同中止", "中止合同");
		}
		//签约时段  将销售计划模板置为无效
		for (TbBizPlaceBuyContractDetail detailVo : detailVoList) {
			TbBizPlaceUnitSalePlanMainExample placeUnitSalePlanMainExample = new TbBizPlaceUnitSalePlanMainExample();
			TbBizPlaceUnitSalePlanMainExample.Criteria criteria = placeUnitSalePlanMainExample.createCriteria();
			criteria.andPlaceIdEqualTo(detailVo.getPlaceId());
			criteria.andPlaceUnitIdEqualTo(detailVo.getPlaceUnitId());
			if (detailVo.getBuyStartTime() != null) {
				criteria.andStartTimeEqualTo(detailVo.getBuyStartTime());
			}
			if (detailVo.getBuyEndTime() != null) {
				criteria.andEndTimeEqualTo(detailVo.getBuyEndTime());
			}
			TbBizPlaceUnitSalePlanMain tbBizPlaceUnitSalePlanMain = new TbBizPlaceUnitSalePlanMain();
			tbBizPlaceUnitSalePlanMain.setIsEffective(PlaceConstants.IS_EFFECTIVE_NO);
			tbBizPlaceUnitSalePlanMainMapper.updateByExampleSelective(tbBizPlaceUnitSalePlanMain, placeUnitSalePlanMainExample);
		}
		contractService.updateSolrIndex(reqVo.getPlaceId());
		return APIResponse.returnSuccess();
	}


	/**
	 * 导出合同列表
	 *
	 * @param reqVo
	 * @return
	 */
	@Override
	public List<RespPlaceContractInfoVo> expotrContractList(ReqPlaceContractInfoVo reqVo) {
		return contractService.expotrContractList(reqVo);
	}

	@Override
	public boolean updateSolrIndex(Integer placeId) {
		return contractService.updateSolrIndex(placeId);
	}

	/**
	 * solr导入场馆索引
	 *
	 * @param map
	 * @param solrUrl
	 * @return
	 */
	public String importIndexByTerm(Map map, String solrUrl) {
		try {
			Integer opType = MapUtils.getInteger(map, "type");
			Integer placeId = MapUtils.getInteger(map, "placeId");

			if (PlaceConstants.SOLR_INDEX_PLACE == opType) {
				this.delSolrPlaceIndex(placeId);
				searchService.addPlaceSaleIndex(placeId);
			} else {
				this.delSolrPlaceIndex(placeId);
				this.delSolrSaleIndex(placeId);
				searchService.addPlaceSaleIndex(placeId);
			}
			return "导入场馆索引成功";
		} catch (Exception e) {
			e.printStackTrace();
			return "导入场馆索引失败:" + e.getMessage();
		}
	}

	public String importPlacesIndex(String placeIds) {
		if (!StringUtils.isEmpty(placeIds)) {
			try {
				String[] ids = org.apache.commons.lang3.StringUtils.split(placeIds, ",");
				for (int i = 0; i < ids.length; i++) {
					int placeId = Integer.parseInt(ids[i]);
					this.delSolrPlaceIndex(placeId);
					this.delSolrSaleIndex(placeId);
					searchService.addPlaceSaleIndex(placeId);
				}
				return "导入场馆索引成功";
			} catch (Exception e) {
				return "导入场馆索引失败:" + placeIds;
			}
		}
		return "参数错误";
	}

	@Override
	public APIResponse<?> importIndex(Map map) {
		return searchService.importIndex(map);
	}

	/**
	 * 同步场馆销售计划到搜索引擎
	 *
	 * @param placeId
	 * @return
	 */
	@Override
	public APIResponse<?> syncPlaceSalePlanToSearchEngine(Integer placeId) {
		searchService.addPlaceSaleIndex(placeId);
		return APIResponse.returnSuccess();
	}

	@Override
	@Async
	public void setPlaceIdToCache(Integer placeId, PlaceRedisTemplate placeRedisTemplate) {
		// 将更新过价格的场馆放入Redis
		RedisKey redisKey = new RedisKey(RedisConstants.PLACE_FAMILY_KEY, PlaceConstants.PLACE_SYNC_SOLR_PREFIX);
		Set<Integer> placeIdSet = Collections.synchronizedSet(new HashSet<Integer>());
		if (!placeRedisTemplate.exists(redisKey)) {
			placeIdSet.add(placeId);
			placeRedisTemplate.setWithExpireTime(redisKey, placeIdSet, 24 * 60 * 60);
		} else {
			Object o = null;
			try {
				o = placeRedisTemplate.get(redisKey);
			} catch (Exception e) {
				logger.error("查询缓存异常，key={},{}", redisKey.getRedisKey(), e.getMessage());
			}
			placeIdSet = (Set) o;
			placeIdSet.add(placeId);
			placeRedisTemplate.setWithExpireTime(redisKey, placeIdSet, 24 * 60 * 60);
		}
	}

	public void updateContractStatus() {
		contractService.updateContractStatus();
	}

	@Override
	public APIResponse<?> addPlaceBuyContract(PlaceBuyContract placeBuyContract) {
		APIResponse result = placeBuyService.addPlaceBuyContract(placeBuyContract);

		if (result.isRet()) {
			// 将新签约的合同备份到History中
			importContractIntoHistory(placeBuyContract.getId());
		}

		return result;
	}

	public boolean isExistsPlace(Integer placeId) {
		return placeBaseService.isExistsPlace(placeId);
	}


	@Override
	public APIResponse<?> getContractPayList(Integer contractId) {
		return contractService.getContractPayList(contractId);
	}

	@Override
	public APIResponse<?> updateContractPay(ReqContractPay reqVo) {
		return contractService.updateContractPay(reqVo);
	}

	@Override
	public APIResponse<?> deleteContractPay(ReqContractPay reqVo) {
		return contractService.deleteContractPay(reqVo);
	}

	/**
	 * 插入推送场地预定短信相关的数据
	 *
	 * @param reqPlaceMessageVo
	 */
	@Override
	public APIResponse<?> insertMessageData(ReqPlaceMessageVo reqPlaceMessageVo) {
		return APIResponse.returnSuccess(placeMessageService.insertMobileData(reqPlaceMessageVo));
	}

	/**
	 * 查询短信相关的数据
	 *
	 * @param placeId
	 * @return
	 */
	@Override
	public APIResponse<?> getMessageDataByPlaceId(Integer placeId) {
		return APIResponse.returnSuccess(placeMessageService.getMobileDataByPlaceId(placeId));
	}

	/**
	 * 删除数据
	 *
	 * @param reqPlaceMessageVo
	 * @return
	 */
	@Override
	public APIResponse<?> deleteMessageData(ReqPlaceMessageVo reqPlaceMessageVo) {
		return APIResponse.returnSuccess(placeMessageService.deleteMobileData(reqPlaceMessageVo));
	}

	/**
	 * 设置场馆运动项目最小销售单元
	 *
	 * @param placeId
	 * @param categoryId
	 * @param timeUnit
	 * @return
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public APIResponse setPlaceCategorySaleTimeUnit(Integer placeId, Integer categoryId, Byte timeUnit, Byte startSaleTimeType) {
		TbBizPlaceCategory dbPlaceCategory = placeBaseService.getPlaceCategory(placeId, categoryId);
		boolean updateRet = placeBaseService.setPlaceCategorySaleTimeUnit(placeId, categoryId, timeUnit, startSaleTimeType);
		boolean isTimeChanged = false;

		// 运动项目已经设置过价格的不允许半点切为整点
		if (placeBaseService.isAnyPrice(placeId, categoryId) && Constants.BYTE_ONE == timeUnit){
			// 半点 切换为整点
			return APIResponse.returnFail("当前运动项目不允许将半点销售切换为整点销售");
		}
		// 销售单元变更
		if (updateRet && null != dbPlaceCategory){
			if (null != dbPlaceCategory.getStartSaleTimeType() &&
					!startSaleTimeType.equals(dbPlaceCategory.getStartSaleTimeType())){
				// 如果运动项目起售时间有变更
				isTimeChanged = true;
				// 删除场地销售时段
				this.deletePlaceUnitTime(placeId, categoryId);
			}
			if (null != dbPlaceCategory.getMinSaleTimeUnit() &&
					!timeUnit.equals(dbPlaceCategory.getMinSaleTimeUnit())){

				isTimeChanged = true;
				// 整点切换成半点时
				if (Constants.BYTE_ZERO == timeUnit){
					// 已经预定出去的场地，原来的整点时段切割成半点
					try {
						placeInnerService.splitSalePlanAlreadyBooked(placeId,categoryId);
					} catch (Exception e) {
						logger.error("placeId:" + placeId + " 整点切半点销售" + e.toString());
						e.printStackTrace();
					}
				}
			}
			if (isTimeChanged){
				// 原销售计划模板置为无效
				placeInnerService.updateSalePlanMainToInvalidate(placeId, categoryId);
				// 销售计划置为无效
				placeInnerService.updateSalePlanToInvalidateByCategroyId(placeId, categoryId);
			}
		}
		return APIResponse.returnSuccess();
	}

	/**
	 * 根据场馆运动项目删除销售时段
	 * @param placeId
	 * @param categoryId
     */
	public void deletePlaceUnitTime(Integer placeId, Integer categoryId) {
		if (null != categoryId){
			byte byteCategoryId = (byte)categoryId.intValue();
			List<TbBizPlaceUnit> placeUnitList = placeBaseService.getPlaceUnitByPlaceId(placeId, byteCategoryId, false);
			List<Integer> placeUnitIdList = new ArrayList<Integer>();
			for (TbBizPlaceUnit unit : placeUnitList){
				placeUnitIdList.add(unit.getId());
			}
			if (null == placeUnitIdList || placeUnitIdList.size() == 0){
				return;
			}
			placeInnerService.deletePlaceUnitTime(placeId, placeUnitIdList);
		}
	}

	@Override
	public List<RespPlaceClubInfo> selectClubByPlaceIds(Integer placeId, Integer number) {
		List<RespPlaceClubInfo> respPlaceClubInfoList = new ArrayList<>();
		List<Integer> placeIds = new ArrayList<>();
		placeIds.add(placeId);
		Map<Integer, RespPlaceClubInfo> map = new HashMap<>();
		Map<Integer, List<RespPlaceClubInfo>> clubMap = clubOpenService.selectClubByPlaceIds(placeIds, 1, number, 0);
		if (MapUtils.isEmpty(clubMap)) {
			return respPlaceClubInfoList;
		}
		return clubMap.get(placeId);
	}

	@Override
	public List<RespPlaceClubInfo> selectActivityByPlaceIds(Integer placeId, Integer number) {
		List<RespPlaceClubInfo> respPlaceClubInfoList = new ArrayList<>();
		List<Integer> placeIds = new ArrayList<>();
		placeIds.add(placeId);
		Map<Integer, RespPlaceClubInfo> map = new HashMap<>();
		Map<Integer, List<RespPlaceClubInfo>> clubMap = clubOpenService.selectActivityByPlaceIds(placeIds, 1, number, 0);
		if (MapUtils.isEmpty(clubMap)) {
			return respPlaceClubInfoList;
		}
		return clubMap.get(placeId);
	}

	@Override
	public List<RespPlaceVideoInfo> getPlaceVideoInfo(Integer placeId, Integer number) {
		List<RespPlaceVideoInfo> respPlaceVideoInfos = new ArrayList<>();

		APIResponse<List<RespPlaceVideoInfo>> response = videoServiceFacade.getPlaceVideosByPlaceId(placeId, number);
		if (!response.isRet()) {
			return respPlaceVideoInfos;
		}
		List<RespPlaceVideoInfo> respPlaceVideoInfoList = response.getData();
		if (CollectionUtils.isEmpty(respPlaceVideoInfoList)) {
			return respPlaceVideoInfos;
		}
		return respPlaceVideoInfoList;
	}

	public RespPlaceClubActivity findPlaceVC(@NotNull Integer placeId) {
		RespPlaceClubActivity respPlaceClubActivity = new RespPlaceClubActivity();

		try {
			//场馆关联视频
			List<RespPlaceVideoInfo> respPlaceVideoInfos = this.getPlaceVideoInfo(placeId, 10);
			//场馆关联俱乐部
			List<RespPlaceClubInfo> respPlaceClubInfos = this.selectClubByPlaceIds(placeId, 5);
			//场馆关联俱乐部活动
			List<RespPlaceClubInfo> respActivityClubInfos = this.selectActivityByPlaceIds(placeId, 5);
			//场馆关联达人活动
			List<GatherPlaceResponse> respMasters = this.getMasterByPlaceId(placeId, 0, 10);

			if (CollectionUtils.isNotEmpty(respPlaceVideoInfos)) {
				respPlaceClubActivity.setRespPlaceVideoInfos(respPlaceVideoInfos);
			}
			if (CollectionUtils.isNotEmpty(respPlaceClubInfos)) {
				respPlaceClubActivity.setRespPlaceClubInfos(respPlaceClubInfos);
			}
			if (CollectionUtils.isNotEmpty(respActivityClubInfos)) {
				respPlaceClubActivity.setRespActivityClubInfos(respActivityClubInfos);
			}
			if (CollectionUtils.isNotEmpty(respMasters)) {
				respPlaceClubActivity.setRespMasters(respMasters);
			}

		} catch (Exception e) {
			logger.error("场馆关联视频/关联俱乐部/关联俱乐部活动/关联达人活动异常:{}", e);
		}
		return respPlaceClubActivity;

	}

	@Override
	public List<GatherPlaceResponse> getMasterByPlaceId(@NotNull Integer placeId, Integer pageNum, Integer pageSize) {
		List<Integer> placeIds = new ArrayList<>();
		placeIds.add(placeId);
		return iPlaceDubboService.getGatherPlaceInfo(placeIds, pageNum, pageSize);
	}


	/**
	 * app端获取场馆
	 * 判断场馆是否有活动
	 *
	 * @param reqPlaceSalePlan
	 * @return
	 */
	@Override
	public APIResponse<RespPlaceUnitSalePlanDetail> getPlaceSalePlan(ReqPlaceSalePlan reqPlaceSalePlan) {
		APIResponse<RespPlaceUnitSalePlanDetail> placeOrderService = apiPlaceOrderSerive.getPlaceSalePlan(reqPlaceSalePlan);
		try {
			RedisKey rediskey = new RedisKey(RedisConstants.PLACE_FAMILY_KEY,
					reqPlaceSalePlan.getPlaceId() + PlaceConstants.PLACE_VIDEO_CLUB_MASTER_KEY);
			Object obj = placeRedisTemplate.get(rediskey);
			RespPlaceUnitSalePlanDetail placeUnitSalePlanDetail = placeOrderService.getData();
			if (obj != null && NumberUtils.isDigits(obj + "")) {
				placeUnitSalePlanDetail.setPlaceActivity(Integer.parseInt(obj + ""));
			} //else {
//				int placeActivityStatus = getPlaceActivityStatus(reqPlaceSalePlan.getPlaceId());
//				placeUnitSalePlanDetail.setPlaceActivity(placeActivityStatus);
//				placeRedisTemplate.set(rediskey, String.valueOf(placeActivityStatus));
//			}
		} catch (Exception e) {
			logger.error("场馆关联视频/关联俱乐部/关联俱乐部活动/关联达人活动异常:{}", e);
		}
		return placeOrderService;

		/*if (null != placeOrderService) {
				Integer placeId = reqPlaceSalePlan.getPlaceId();
				List<Integer> placeIds = new ArrayList<>();
				placeIds.add(placeId);

				Integer pageNum = 1;
				Integer pageSize = 100;
				List<GatherPlaceResponse> gatherList = iPlaceDubboService.getGatherPlaceInfo(placeIds, pageNum - 1, pageSize);
				if (null != gatherList && gatherList.size() > 0) {
					placeUnitSalePlanDetail.setPlaceActivity(1);
					return placeOrderService;
				}
				Map<Integer, List<RespPlaceClubInfo>> clubMap = clubOpenService.selectClubByPlaceIds(placeIds, pageNum, pageSize);
				if (null != clubMap && clubMap.size() > 0) {
					placeUnitSalePlanDetail.setPlaceActivity(1);
					return placeOrderService;
				}
				Map<Integer, List<RespPlaceClubInfo>> activityMap = clubOpenService.selectActivityByPlaceIds(placeIds, pageNum, pageSize);
				if (null != activityMap && activityMap.size() > 0) {
					placeUnitSalePlanDetail.setPlaceActivity(1);
					return placeOrderService;
				}

				APIResponse<List<RespPlaceVideoInfo>> response = videoServiceFacade.getPlaceVideosByPlaceId(placeId, pageSize);
				if (null != response && null != response.getData() && response.getData().size() > 0) {
					placeUnitSalePlanDetail.setPlaceActivity(1);
					return placeOrderService;
				}

			}
		return null;*/



	}
}
